package ossaliyun

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"monitor_serve/config"
)

var ossCli *oss.Client

func alyOsClient() *oss.Client {
	if ossCli != nil {
		return ossCli
	}
	ossCli, err := oss.New(config.OSSEndpoint, config.OSSAccessKey, config.OSSSecretKey)
	if err != nil {
		fmt.Println("Failed to create oss client, err:", err)
		return nil
	}
	return ossCli
}

// 获取bucket存储空间
func GetBucket() *oss.Bucket {
	cli := alyOsClient()
	if cli == nil {
		return nil
	}
	bucket, err := cli.Bucket(config.OSSBucket)
	if err != nil {
		fmt.Println("Failed to get bucket, err:", err)
		return nil
	}
	return bucket
}

// 临时授权下载url
func DownloadUrl(objName string) string {
	signUrl, err := GetBucket().SignURL(objName, oss.HTTPGet, 3600)
	if err != nil {
		fmt.Println(err)
	}

	return signUrl
}

// 生命周期
func BuildLifeCycleRule(bucketName string) {
	//表示前缀为test的对象距最后修改时间30天后过期
	ruleTest1 := oss.BuildLifecycleRuleByDays("rule1", "test/", true, 30)
	rules := []oss.LifecycleRule{ruleTest1}
	alyOsClient().SetBucketLifecycle(bucketName, rules)
}
